package com.learn;

import static org.junit.Assert.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.io.IOUtils;
import org.junit.Test;

/**
 * @说明 从网络获取图片到本地
 * @author 崔素强
 * @version 1.0
 * @since
 */
/**
 * @author Administrator
 *
 */
public class GetImage {
	/**
	 * 测试
	 * 
	 * @param args
	 *            org.apache.commons.io.IOUtils的类 还有个FileUtils 都蛮好用的
	 *            不需要自己用字节读文件了
	 */
	public static void main(String[] args) throws Exception {
		String url = "http://www.baidu.com/img/baidu_sylogo1.gif";
		// byte[] btImg = getImageFromNetByUrl(url);
//		String fileurl = "file:/D:/xingyou-project/zliudi-project/wms/bin/services/wms/OutboundDownload/shipment.pdf";
		InputStream in = new URL(url).openStream();
		byte[] btImg = readInputStream(in);
		if (null != btImg && btImg.length > 0) {
			System.out.println("读取到：" + btImg.length + " 字节");
			writeImageToDisk(btImg,
					"d:\\cngold-img\\aaaa" + (int) (Math.random() * 1000)
							+ ".jpg");
		} else {
			System.out.println("没有从该连接获得内容");
		}
	}

	/**
	 * 将图片写入到磁盘
	 * 
	 * @param img
	 *            图片数据流
	 * @param fileName
	 *            文件保存时的名称
	 */
	public static void writeImageToDisk(byte[] img, String fileName) {
		try {
			File file = new File(fileName);
			FileOutputStream fops = new FileOutputStream(file);
			fops.write(img);
			fops.flush();
			fops.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据地址获得数据的字节流
	 * 
	 * @param strUrl
	 *            网络连接地址
	 * @return
	 */
	public static byte[] getImageFromNetByUrl(String strUrl) {
		try {
			URL url = new URL(strUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
			byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
			return btImg;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 从输入流中获取数据
	 * 
	 * @param inStream
	 *            输入流
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}

	/**
	 * 2016-12-14 测试的post传输文件下载
	 */
	@Test
	public void SendPostDemo() throws Exception {
		String html = "aaa";
		URL url = new URL("http://pdf.starpost.cn");
		HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
		httpConn.setInstanceFollowRedirects(true);  
		httpConn.setDoOutput(true);
		HttpURLConnection.setFollowRedirects(true);
		httpConn.setDoInput(true);
		httpConn.setUseCaches(false);
		httpConn.setConnectTimeout(1000);
		httpConn.setRequestMethod("POST");
		httpConn.setRequestProperty("User-Agent", "Mozilla");
		httpConn.setRequestProperty("Page-Width", "100");
		httpConn.setRequestProperty("Page-Height", "100");
		httpConn.setRequestProperty("Margin-Top", "0");
		httpConn.setRequestProperty("Margin-Bottom", "0");
		httpConn.setRequestProperty("Margin-Left", "0");
		httpConn.setRequestProperty("Margin-Right", "0");
		httpConn.setRequestProperty("Content-Type", "text/html");
		httpConn.connect();
		DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
		dos.writeBytes(new String(html.getBytes("utf-8")));
		dos.flush();
		dos.close();
		int resultCode = httpConn.getResponseCode();
		System.out.println(resultCode);
		if (HttpURLConnection.HTTP_OK == resultCode) {
			byte[] result = IOUtils.toByteArray(httpConn.getInputStream());
			return ;
		}
		System.out.println("null....");
	}
	
	public void test2() throws Exception {
		// 方法一 
        URL url = new URL("http://www.sina.com.cn");
        URLConnection urlcon = url.openConnection();
        InputStream is = urlcon.getInputStream();
       
         // 方法二
        URL url2 = new URL("http://www.yhfund.com.cn");
        HttpURLConnection urlcon2 = (HttpURLConnection)url2.openConnection();
        InputStream is2 = urlcon2.getInputStream();
       
        //方法三
        URL url3 = new URL("http://www.yhfund.com.cn");
        InputStream is3 = url3.openStream();
	}
	
	public void test3() throws Exception{
		String url = "https://ls.starpost.cn/starpost/PrintLabelAction?printType=pdf&label_spec=100x100&scanno=SP329489477";
		byte[] btImg = null;
		try {
			InputStream in = new URL(url).openStream();
			byte[] b = IOUtils.toByteArray(in);
			System.out.println(b.length);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}